<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>SVG拼接工具</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 20px;
            background-color: #f8f9fa;
        }
        .container {
            display: flex;
            flex-direction: column;
            align-items: center;
            gap: 20px;
            max-width: 1200px;
            margin: 0 auto;
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        .input-area {
            display: flex;
            gap: 10px;
            align-items: center;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 8px;
            width: 100%;
            max-width: 800px;
            justify-content: center;
        }
        .svg-container {
            border: 1px solid #ccc;
            padding: 20px;
            margin-top: 20px;
            width: 100%;
            max-width: 1100px;
            min-height: 700px;
            position: relative;
            background-color: white;
            border-radius: 4px;
        }
        #result-svg {
            width: 100%;
            height: 100%;
            min-height: 600px;
        }
        .preview-container {
            display: flex;
            gap: 30px;
            margin-top: 20px;
            flex-wrap: wrap;
            justify-content: center;
        }
        .preview {
            border: 1px solid #ddd;
            padding: 15px;
            text-align: center;
            background-color: white;
            border-radius: 4px;
            box-shadow: 0 1px 5px rgba(0,0,0,0.05);
        }
        .preview svg {
            max-width: 100px;
            max-height: 200px;
        }
        .status {
            color: #0d6efd;
            margin: 15px 0;
            text-align: center;
            padding: 10px;
            background-color: #f8f9fa;
            border-radius: 4px;
            width: 100%;
            max-width: 800px;
        }
        .error {
            color: #dc3545;
            background-color: #f8d7da;
        }
        .success {
            color: #198754;
            background-color: #d1e7dd;
        }
        #loading-status {
            margin-top: 10px;
            padding: 10px 15px;
            border-radius: 4px;
            font-weight: 500;
        }
        button {
            padding: 8px 16px;
            border-radius: 4px;
            border: none;
            cursor: pointer;
            font-weight: 500;
            transition: all 0.2s;
        }
        button:hover {
            opacity: 0.9;
        }
        button:disabled {
            opacity: 0.6;
            cursor: not-allowed;
        }
        input[type="text"] {
            padding: 8px 12px;
            border: 1px solid #ced4da;
            border-radius: 4px;
            width: 120px;
        }
        #generate-btn {
            background-color: #0d6efd;
            color: white;
        }
        .instructions {
            margin: 15px 0;
            text-align: center;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 4px;
            max-width: 800px;
            border-left: 4px solid #0d6efd;
        }
        .example-buttons {
            margin: 15px 0;
            display: flex;
            justify-content: center;
            flex-wrap: wrap;
        }
        .example-buttons button {
            margin: 5px;
            background-color: #6c757d;
            color: white;
        }
        h1 {
            color: #0d6efd;
            border-bottom: 2px solid #e9ecef;
            padding-bottom: 10px;
            width: 100%;
            text-align: center;
        }
    </style>
</head>
<body>
    <div class="container">
        <h1>SVG拼接工具</h1>
        
        <div id="loading-status" class="status">正在加载SVG文件...</div>
        
        <div class="input-area">
            <label for="pattern-input">输入拼接模式：</label>
            <input type="text" id="pattern-input" placeholder="例如: 2,3" />
            <button onclick="generateSVG()" id="generate-btn" disabled>生成</button>
            <button onclick="reloadSVGs()" id="reload-btn" style="margin-left: 10px; background-color: #6c757d; color: white;">刷新SVG</button>
        </div>
        
        <div class="instructions">
            <p><strong>使用说明:</strong></p>
            <p>1. 输入格式为: <code>上面1.svg的数量,下面2.svg的数量</code>，如 <code>2,3</code></p>
            <p>2. 第一个数字表示上方1.svg的数量</p>
            <p>3. 第二个数字表示下方2.svg的数量</p>
            <p>4. 中间始终是3.svg作为横向分隔线</p>
        </div>
        
        <div class="preview-container">
            <div class="preview">
                <h3>1.svg</h3>
                <div id="preview-1">
                    <object type="image/svg+xml" data="SVG/1.svg" width="100" height="200"></object>
                </div>
            </div>
            <div class="preview">
                <h3>2.svg</h3>
                <div id="preview-2">
                    <object type="image/svg+xml" data="SVG/2.svg" width="100" height="200"></object>
                </div>
            </div>
            <div class="preview">
                <h3>3.svg</h3>
                <div id="preview-3">
                    <object type="image/svg+xml" data="SVG/3.svg" width="100" height="30"></object>
                </div>
            </div>
        </div>
        
        <div class="svg-container">
            <div id="result-svg"></div>
            <div style="margin-top: 20px; text-align: center;">
                <button id="download-btn" style="background: #198754; color: white; padding: 10px 20px; font-size: 16px; display: none;">下载SVG</button>
            </div>
        </div>
    </div>
    
    <script>
        // SVG内容缓存 - 用于生成组合SVG
        const svgCache = {
            '1': '',
            '2': '',
            '3': ''
        };
        
        // 页面加载完成后加载SVG文件
        window.onload = function() {
            // 使用XHR加载SVG
            loadSVGsWithXHR();
            
            // 添加示例按钮
            addExampleButtons();
        };
        
        // 使用XMLHttpRequest加载SVG
        function loadSVGsWithXHR() {
            const loadingStatus = document.getElementById('loading-status');
            const generateBtn = document.getElementById('generate-btn');
            let loadedCount = 0;
            
            for (let i = 1; i <= 3; i++) {
                const xhr = new XMLHttpRequest();
                xhr.open('GET', `SVG/${i}.svg`, true);
                
                // 设置正确的响应类型
                xhr.responseType = 'text';
                
                xhr.onload = function() {
                    if (xhr.status === 200) {
                        svgCache[i] = xhr.responseText;
                        loadedCount++;
                        console.log(`SVG ${i} 已加载成功 (${loadedCount}/3)`);
                        
                        loadingStatus.textContent = `已加载 ${loadedCount}/3 个SVG文件`;
                        
                        // 检查是否所有SVG都已加载
                        if (loadedCount === 3) {
                            console.log('所有SVG文件已加载完成');
                            loadingStatus.textContent = '所有SVG文件已加载完成，可以开始拼接';
                            loadingStatus.className = 'status success';
                            generateBtn.disabled = false;
                        }
                    } else {
                        console.error(`无法加载SVG ${i}, 状态: ${xhr.status}`);
                        loadingStatus.textContent = `无法加载SVG/${i}.svg, 状态码: ${xhr.status}`;
                        loadingStatus.className = 'status error';
                    }
                };
                
                xhr.onerror = function() {
                    console.error(`加载SVG ${i} 时出错`);
                    loadingStatus.textContent = `加载SVG/${i}.svg 时出错，请检查文件是否存在`;
                    loadingStatus.className = 'status error';
                };
                
                xhr.send();
            }
        }
        
        // 重新加载SVG
        function reloadSVGs() {
            const loadingStatus = document.getElementById('loading-status');
            loadingStatus.textContent = '正在重新加载SVG文件...';
            loadingStatus.className = 'status';
            document.getElementById('generate-btn').disabled = true;
            document.getElementById('result-svg').innerHTML = '';
            document.getElementById('download-btn').style.display = 'none';
            
            // 清空缓存
            svgCache['1'] = '';
            svgCache['2'] = '';
            svgCache['3'] = '';
            
            loadSVGsWithXHR();
        }
        
        // 生成拼接SVG
        function generateSVG() {
            const patternInput = document.getElementById('pattern-input').value.trim();
            if (!patternInput) {
                alert('请输入拼接模式');
                return;
            }
            
            // 解析输入
            const pattern = parsePattern(patternInput);
            if (!pattern) {
                alert('无效的拼接模式，请使用格式如"2,3"');
                return;
            }
            
            // 确保SVG已加载
            if (!svgCache['1'] || !svgCache['2'] || !svgCache['3']) {
                alert('SVG文件未完全加载，请等待或刷新页面');
                return;
            }
            
            // 更新状态信息
            const loadingStatus = document.getElementById('loading-status');
            loadingStatus.textContent = `正在生成拼接图: 上方${pattern.top}个, 下方${pattern.bottom}个`;
            
            // 创建最终SVG
            const resultContainer = document.getElementById('result-svg');
            resultContainer.innerHTML = '';
            
            // 调整SVG的大小和比例
            // 创建新的SVG元素
            const combinedSvg = document.createElementNS("http://www.w3.org/2000/svg", "svg");
            combinedSvg.setAttribute("xmlns", "http://www.w3.org/2000/svg");
            combinedSvg.setAttribute("width", "100%");
            combinedSvg.setAttribute("height", "100%");
            combinedSvg.setAttribute("viewBox", "0 0 1200 500");
            combinedSvg.setAttribute("id", "combined-svg");
            
            // 添加样式
            const styleElement = document.createElementNS("http://www.w3.org/2000/svg", "style");
            styleElement.textContent = `
                .cls-1 {
                    fill: none;
                    stroke: #000;
                    stroke-linecap: round;
                    stroke-miterlimit: 10;
                    stroke-width: 2.83px;
                }
                .cls-2 {
                    fill: #000;
                }
            `;
            combinedSvg.appendChild(styleElement);
            
            // 创建主组
            const mainGroup = document.createElementNS("http://www.w3.org/2000/svg", "g");
            mainGroup.setAttribute("id", "combined-group");
            
            try {
                // 解析SVG字符串为文档
                const parser = new DOMParser();
                
                // 获取各个SVG的文档
                const svg1Doc = parser.parseFromString(svgCache['1'], "image/svg+xml");
                const svg2Doc = parser.parseFromString(svgCache['2'], "image/svg+xml");
                const svg3Doc = parser.parseFromString(svgCache['3'], "image/svg+xml");
                
                // 获取各个SVG的主要内容组
                const svg1Group = svg1Doc.querySelector("g > g").cloneNode(true);
                const svg2Group = svg2Doc.querySelector("g > g").cloneNode(true);
                const svg3Group = svg3Doc.querySelector("g > g").cloneNode(true);
                
                // 放置上方的1.svg元素
                const topCount = parseInt(pattern.top) || 2; // 默认2个
                
                // 均匀分布在中间的两侧
                if (topCount === 1) {
                    // 如果只有1个，放在中间
                    const topGroup = svg1Group.cloneNode(true);
                    // 微调位置，确保完全在中间线上方且不相交
                    topGroup.setAttribute("transform", `translate(600, 15) scale(0.65)`);
                    mainGroup.appendChild(topGroup);
                } else {
                    // 计算左右分布
                    const leftCount = Math.floor(topCount / 2);
                    const rightCount = topCount - leftCount;
                    
                    // 确定左侧间距
                    const leftSpacing = 400 / (leftCount + 1);
                    for (let i = 0; i < leftCount; i++) {
                        const topGroup = svg1Group.cloneNode(true);
                        const xPos = 200 + (i + 1) * leftSpacing;
                        // 微调位置，确保完全在中间线上方且不相交
                        topGroup.setAttribute("transform", `translate(${xPos}, 15) scale(0.65)`);
                        mainGroup.appendChild(topGroup);
                    }
                    
                    // 确定右侧间距
                    const rightSpacing = 400 / (rightCount + 1);
                    for (let i = 0; i < rightCount; i++) {
                        const topGroup = svg1Group.cloneNode(true);
                        const xPos = 600 + (i + 1) * rightSpacing;
                        // 微调位置，确保完全在中间线上方且不相交
                        topGroup.setAttribute("transform", `translate(${xPos}, 15) scale(0.65)`);
                        mainGroup.appendChild(topGroup);
                    }
                }
                
                // 创建中间的横向分隔线 - 根据实际的3.svg内容
                const middleGroup = document.createElementNS("http://www.w3.org/2000/svg", "g");
                middleGroup.setAttribute("id", "middle-divider");
                
                // 修改线条位置，确保元素完美连接
                // 左侧长线
                const leftLine = document.createElementNS("http://www.w3.org/2000/svg", "line");
                leftLine.setAttribute("x1", "50");
                leftLine.setAttribute("y1", "180");
                leftLine.setAttribute("x2", "590");
                leftLine.setAttribute("y2", "180");
                leftLine.setAttribute("stroke", "#000");
                leftLine.setAttribute("stroke-width", "2.83");
                leftLine.setAttribute("stroke-linecap", "round");
                leftLine.setAttribute("class", "cls-2");
                middleGroup.appendChild(leftLine);
                
                // 右侧长线
                const rightLine = document.createElementNS("http://www.w3.org/2000/svg", "line");
                rightLine.setAttribute("x1", "620");
                rightLine.setAttribute("y1", "180");
                rightLine.setAttribute("x2", "1150");
                rightLine.setAttribute("y2", "180");
                rightLine.setAttribute("stroke", "#000");
                rightLine.setAttribute("stroke-width", "2.83");
                rightLine.setAttribute("stroke-linecap", "round");
                rightLine.setAttribute("class", "cls-2");
                middleGroup.appendChild(rightLine);
                
                // 中间断开的连接器
                const middleConnector = document.createElementNS("http://www.w3.org/2000/svg", "g");
                
                // 左侧连接器路径
                const pathsData = [
                    // 左侧第一个路径
                    {d: "M583,171l-8.34,8.5c-.51.52-.48,1.36.06,1.85l8.28,7.47", class: "cls-1"},
                    // 左侧第二个路径
                    {d: "M589,171l-8.34,8.5c-.51.52-.48,1.36.06,1.85l8.28,7.47", class: "cls-1"},
                    // 右侧第一个路径
                    {d: "M629,171l8.34,8.5c.51.52.48,1.36-.06,1.85l-8.28,7.47", class: "cls-1"},
                    // 右侧第二个路径
                    {d: "M623,171l8.34,8.5c.51.52.48,1.36-.06,1.85l-8.28,7.47", class: "cls-1"}
                ];
                
                // 创建路径元素
                pathsData.forEach(data => {
                    const path = document.createElementNS("http://www.w3.org/2000/svg", "path");
                    path.setAttribute("d", data.d);
                    path.setAttribute("class", data.class);
                    path.setAttribute("fill", "none");
                    path.setAttribute("stroke", "#000");
                    path.setAttribute("stroke-linecap", "round");
                    path.setAttribute("stroke-miterlimit", "10");
                    path.setAttribute("stroke-width", "2.83");
                    middleConnector.appendChild(path);
                });
                
                // 创建矩形
                const rect = document.createElementNS("http://www.w3.org/2000/svg", "rect");
                rect.setAttribute("x", "590");
                rect.setAttribute("y", "174");
                rect.setAttribute("width", "32");
                rect.setAttribute("height", "11");
                rect.setAttribute("rx", "2.18");
                rect.setAttribute("ry", "2.18");
                rect.setAttribute("fill", "none");
                rect.setAttribute("stroke", "#000");
                rect.setAttribute("stroke-linecap", "round");
                rect.setAttribute("stroke-miterlimit", "10");
                rect.setAttribute("stroke-width", "2.83");
                rect.setAttribute("class", "cls-1");
                middleConnector.appendChild(rect);
                
                // 创建两个圆
                const circle1 = document.createElementNS("http://www.w3.org/2000/svg", "circle");
                circle1.setAttribute("cx", "601");
                circle1.setAttribute("cy", "180");
                circle1.setAttribute("r", "3");
                circle1.setAttribute("fill", "none");
                circle1.setAttribute("stroke", "#000");
                circle1.setAttribute("stroke-linecap", "round");
                circle1.setAttribute("stroke-miterlimit", "10");
                circle1.setAttribute("stroke-width", "2.83");
                circle1.setAttribute("class", "cls-1");
                middleConnector.appendChild(circle1);
                
                const circle2 = document.createElementNS("http://www.w3.org/2000/svg", "circle");
                circle2.setAttribute("cx", "611");
                circle2.setAttribute("cy", "180");
                circle2.setAttribute("r", "3");
                circle2.setAttribute("fill", "none");
                circle2.setAttribute("stroke", "#000");
                circle2.setAttribute("stroke-linecap", "round");
                circle2.setAttribute("stroke-miterlimit", "10");
                circle2.setAttribute("stroke-width", "2.83");
                circle2.setAttribute("class", "cls-1");
                middleConnector.appendChild(circle2);
                
                // 将连接器添加到中间组
                middleGroup.appendChild(middleConnector);
                
                // 将整个中间组添加到主组
                mainGroup.appendChild(middleGroup);
                
                // 放置下方的2.svg元素，调整位置使其能与上方线条对齐
                const bottomCount = parseInt(pattern.bottom) || 3; // 默认3个
                
                // 均匀分布在中间的两侧
                if (bottomCount === 1) {
                    // 如果只有1个，放在中间
                    const bottomGroup = svg2Group.cloneNode(true);
                    // 微调位置，只让顶部极小部分与中间线接触
                    bottomGroup.setAttribute("transform", `translate(600, 182) scale(0.65)`);
                    mainGroup.appendChild(bottomGroup);
                } else {
                    // 计算左右分布
                    const leftCount = Math.floor(bottomCount / 2);
                    const rightCount = bottomCount - leftCount;
                    
                    // 确定左侧间距
                    const leftSpacing = 400 / (leftCount + 1);
                    for (let i = 0; i < leftCount; i++) {
                        const bottomGroup = svg2Group.cloneNode(true);
                        const xPos = 200 + (i + 1) * leftSpacing;
                        // 微调位置，只让顶部极小部分与中间线接触
                        bottomGroup.setAttribute("transform", `translate(${xPos}, 182) scale(0.65)`);
                        mainGroup.appendChild(bottomGroup);
                    }
                    
                    // 确定右侧间距
                    const rightSpacing = 400 / (rightCount + 1);
                    for (let i = 0; i < rightCount; i++) {
                        const bottomGroup = svg2Group.cloneNode(true);
                        const xPos = 600 + (i + 1) * rightSpacing;
                        // 微调位置，只让顶部极小部分与中间线接触
                        bottomGroup.setAttribute("transform", `translate(${xPos}, 182) scale(0.65)`);
                        mainGroup.appendChild(bottomGroup);
                    }
                }
                
                // 添加主组到SVG
                combinedSvg.appendChild(mainGroup);
                
                // 添加到页面
                resultContainer.appendChild(combinedSvg);
                
                // 更新状态信息
                loadingStatus.textContent = `拼接完成: 上方${pattern.top}个1.svg, 下方${pattern.bottom}个2.svg`;
                loadingStatus.className = 'status success';
                
                // 显示下载按钮
                const downloadBtn = document.getElementById('download-btn');
                downloadBtn.style.display = 'inline-block';
                downloadBtn.onclick = function() {
                    downloadSVG();
                };
                
            } catch (error) {
                console.error('生成SVG时出错:', error);
                alert('生成SVG时出错: ' + error.message);
                resultContainer.innerHTML = '<p>生成SVG失败，请检查控制台错误信息</p>';
            }
        }
        
        // 下载SVG
        function downloadSVG() {
            try {
                const svgEl = document.getElementById('combined-svg');
                if (!svgEl) {
                    alert('找不到SVG元素');
                    return;
                }
                
                // 序列化SVG为字符串
                const serializer = new XMLSerializer();
                let svgString = serializer.serializeToString(svgEl);
                
                // 添加XML声明
                svgString = '<?xml version="1.0" encoding="UTF-8" standalone="no"?>\n' + svgString;
                
                // 创建Blob
                const blob = new Blob([svgString], {type: 'image/svg+xml'});
                
                // 创建下载链接
                const a = document.createElement('a');
                a.href = URL.createObjectURL(blob);
                a.download = 'combined_svg.svg';
                
                // 触发下载
                document.body.appendChild(a);
                a.click();
                document.body.removeChild(a);
                
            } catch (error) {
                console.error('下载SVG时出错:', error);
                alert('下载失败: ' + error.message);
            }
        }
        
        // 解析输入模式
        function parsePattern(input) {
            // 使用逗号分隔, 例如 2,3
            const parts = input.split(',');
            
            if (parts.length === 2) {
                const top = parts[0].trim();
                const bottom = parts[1].trim();
                
                // 验证输入是否为有效的数字
                if (/^\d+$/.test(top) && /^\d+$/.test(bottom)) {
                    return {
                        top,
                        bottom
                    };
                }
            }
            
            return null;
        }
        
        // 添加示例按钮
        function addExampleButtons() {
            const container = document.createElement('div');
            container.className = 'example-buttons';
            container.style.margin = '10px 0';
            
            const examples = [
                { label: '上2下3', value: '2,3' },
                { label: '上3下2', value: '3,2' },
                { label: '上1下4', value: '1,4' }
            ];
            
            examples.forEach(example => {
                const button = document.createElement('button');
                button.textContent = example.label;
                button.style.margin = '0 5px';
                button.style.padding = '5px 10px';
                button.onclick = function() {
                    document.getElementById('pattern-input').value = example.value;
                    generateSVG();
                };
                container.appendChild(button);
            });
            
            // 插入到输入区域后面
            const inputArea = document.querySelector('.input-area');
            inputArea.parentNode.insertBefore(container, inputArea.nextSibling);
        }
    </script>
</body>
</html> 